package com.aaa.springboot.controller;


import com.aaa.springboot.commons.lang.Result;
import com.aaa.springboot.pojo.Book;
import com.aaa.springboot.pojo.vo.BookVO;
import com.aaa.springboot.service.BookService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;

import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.File;

import java.io.IOException;

import java.util.List;
import java.util.UUID;

@RestController
@Slf4j
public class BookController {


    @Autowired
    private BookService bookService;


    /**
     * 查询通过id
     *
     * @param id id
     * @return {@link Result<Book>}
     */
    @GetMapping("/select/{id}")
    public  Result<Book> selectById(@PathVariable("id") Integer id){
        Book book = bookService.selectByPrimaryKey(id);
        return  Result.ok(book);
    }


    /**
     * 查询所有
     *
     * @param page  页面
     * @param limit 限制
     * @return {@link Result<List<BookVO>>}  返回通用的数据格式
     */
    @GetMapping("/selectAll")
    @PreAuthorize(value = "hasAnyAuthority('p1','p3')")
    public Result<List<BookVO>> selectAll(@RequestParam(required = false, defaultValue = "1") Integer page,
                                          @RequestParam(required = false, defaultValue = "10") Integer limit,
                                          String bookname) {

        PageHelper.startPage(page, limit);
        List<BookVO> bookVOS = bookService.selectAll(bookname);

        PageInfo<BookVO> pageInfo = new PageInfo<>(bookVOS, 10);
        return Result.ok(pageInfo.getTotal(), pageInfo.getList());

    }

    //定义真实的上传路径  = "D:" + "/pic/file/"
    @Value("${upp.REAL_PATH}")
    public  String REAL_PATH;
    //访问路径 = "/file/" 在config包中进行了映射
    @Value("${upp.VISIT_PATH}")
    public  String VISIT_PATH;

    /**
     * 上传
     *
     * @param file    文件
     * @param session 会话
     * @return {@link Result}* @throws IOException ioexception
     */
    @PostMapping("/upload")
    @PreAuthorize(value = "hasAnyAuthority('p1','p3')")
    public Result upload(MultipartFile file, HttpSession session) throws IOException {

        //session.invalidate();
        // 进来之前先将这个属性清除
        //session.removeAttribute("filePath");
        File file1 = new File(REAL_PATH);
        // 如果这个目录不存在，则新建
        if (!file1.exists()){
            file1.mkdirs();
        }
        // 获得文件的后缀
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        // 新文件的名称
        String newFileName = UUID.randomUUID().toString().replace("-", "") + "." + extension;
        File files = new File(this.REAL_PATH, newFileName);
        //写入磁盘
        file.transferTo(files);//把文件写入到指定的路径中；
        String filePath = this.VISIT_PATH + newFileName;
        session.setAttribute("filePath", filePath);
        System.out.println(session.getAttribute("filePath"));
        return  Result.ok(filePath);
    }



    /**
     * 插入
     *
     * @param book 书
     * @return {@link Result<Book>}
     */
    @PostMapping("insertBook")
    @PreAuthorize(value = "hasAnyAuthority('p1','p3')")
    public Result<Book> insert(@Validated Book book, HttpSession session) {
        String filePath = (String) session.getAttribute("filePath");
        book.setPic(filePath);
        System.out.println(book);
        int i = bookService.insertSelective(book);
        if (i > 0) {
            return Result.ok();
        }
        return Result.fail();

    }


    /**
     * 修改
     *
     * @param book 书
     * @return {@link Result<Book>}
     */
    @PostMapping("update")
    @PreAuthorize(value = "hasAnyAuthority('p1','p3')")
    public Result<Book> update(@Validated Book book, HttpSession session) {

        String filePath = (String) session.getAttribute("filePath");
        book.setPic(filePath);
        System.out.println(book);

        int i = bookService.updateByPrimaryKeySelective(book);

        if (i > 0) {
            return Result.ok();
        }
        return Result.fail();
    }


    @DeleteMapping("delete")
    @PreAuthorize(value = "hasAnyAuthority('p1','p3')")
    public Result<Book> deleteBookById(Integer id) {
        int i = bookService.deleteByPrimaryKey(id);

        if (i > 0) {
            return Result.ok();
        }

        return Result.fail();
    }
    @DeleteMapping("deleteAll")
    @PreAuthorize(value = "hasAnyAuthority('p1','p3')")
    public Result<Book> deleteBookByIds(String ids) {
        // 去掉最后一个逗号
        String substring = ids.substring(0,ids.length()-1);
        System.out.println(substring);
        String[] split = ids.split(",");
        int i =0;
        for (String s : split) {
            i=bookService.deleteByPrimaryKey(Integer.parseInt(s));
        }

         if (i>0){
             return  Result.ok();
         }

        return Result.fail();
    }

}
